package com.xuhai.blog19.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.xuhai.blog19.admin.dao.CodeDao;
import com.xuhai.blog19.admin.entity.CodeEntity;
import com.xuhai.blog19.admin.service.CodeService;
import com.xuhai.blog19.common.exception.RTException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * @Author PangJunjie
 * @Date 2023/2/6/006
 */
@Service
public class CodeServiceImpl extends ServiceImpl<CodeDao, CodeEntity> implements CodeService {
    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getKaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RTException("uuid不能为空");
        }
        String text = producer.createText();
        CodeEntity code = new CodeEntity();
        code.setCode(text);
        code.setUuid(uuid);
        Date date = new Date();
        date.setMinutes(date.getMinutes() + 5);
        code.setExpires(date);

        this.save(code);
        return producer.createImage(text);
    }

    @Override
    public boolean checkCode(String uuid, String code) {
        CodeEntity codeEntity = this.getById(uuid);
        this.removeById(uuid);
        return codeEntity != null && codeEntity.getCode().equalsIgnoreCase(code) && codeEntity.getExpires().getTime() > System.currentTimeMillis();
    }
}
